package com.CmJava.Dubbo.consumer.proxy;

import com.CmJava.Dubbo.consumer.httpClient.HttpClient;
import com.CmJava.Dubbo.consumer.httpClient.parameters.Invocation;
import com.CmJava.Dubbo.provider.register.remoteRegister.RemoteRegister;
import com.CmJava.Dubbo.provider.register.remoteRegister.URL;
import com.CmJava.Dubbo.provider.sevice.DubboProviderService;

import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;


public class ReferenceFactory {

    @SuppressWarnings("all")
    public static <T> T getReference(Class interfaceClass) {
        HttpClient httpClient = new HttpClient();

        //模拟从注册中心获取dubbo服务的url

        URL dubboUrl = RemoteRegister.getInterfaceUrl(interfaceClass.getName());

        if (dubboUrl != null) {
            return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    //发起post请求
                    Invocation invocation = new Invocation(DubboProviderService.class.getName(), method.getName(), method.getParameterTypes(), args);
                    String result = httpClient.post(dubboUrl.getHostName(), dubboUrl.getPort(), dubboUrl.getDubboPath(), invocation);

                    return result;
                }
            });
        }else {
            return null;
        }
    }
}
